import { defineStore } from 'pinia'
import { userProfile, logoutAPI, getShopUserInfo } from "~/api/user";
import { listByIds } from "~/api/oss";

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: {},
    token: '',
    hasShop: false, // 添加 hasShop 字段
    hasCompany: false,
    isLoggingOut: false // 添加标志位防止重复logout
  }),
  getters: {
    isLogin: (state) => {
      // 优先使用 state 中的 token，如果没有则从 localStorage 获取
      if (state.token) return true
      // 在 SSR 环境下安全地获取 token
      if (process.client) {
        const token = localStorage.getItem('token')
        if (token) {
          state.token = token
          return true
        }
      }
      return false
    },
    getToken: (state) => {
      if (state.token) return state.token
      if (process.client) {
        const token = localStorage.getItem('token')
        if (token) {
          state.token = token
          return token
        }
      }
      return null
    },
    getUserInfo: (state) => {
      // 如果 state 中有用户信息且不为空，直接返回
      if (state.userInfo && Object.keys(state.userInfo).length > 0) return state.userInfo
      // 否则从 localStorage 获取
      if (process.client) {
        const userInfo = localStorage.getItem('userInfo')
        if (userInfo) {
          try {
            const parsedUserInfo = JSON.parse(userInfo)
            // 同时更新 state 中的用户信息
            state.userInfo = parsedUserInfo
            return parsedUserInfo
          } catch (e) {
            console.error('解析用户信息失败:', e)
          }
        }
      }
      return {}
    },
    getNickName: (state) => {
      return state.userInfo?.nickname || state.userInfo?.nickName || state.userInfo?.username || ''
    },
    getHasShop: (state) => {
      return state.hasShop
    }
    ,
    getHasCompany: (state) => {
      return state.hasCompany
    }
  },
  actions: {
    setToken(token) {
      this.token = token;
      if (process.client) {
        localStorage.setItem('token', token)
      }
      return Promise.resolve(token)
    },
    setUserInfo(userInfo) {
      this.userInfo = userInfo;
      if (process.client) {
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
      }
      return Promise.resolve(userInfo)
    },
    async logout() {
      // 防止重复调用logout
      if (this.isLoggingOut) {
        console.log('logout already in progress, skipping...');
        return;
      }

      this.isLoggingOut = true;

      try {
        // 调用退出登录接口
        await logoutAPI()
      } catch (error) {
        console.error('退出登录接口调用失败:', error)
        // 如果logout API返回401，不要再次触发logout
        if (error?.response?.status === 401 || error?.response?.data?.code === 401) {
          console.log('logout API返回401，直接清除本地存储');
        }
      } finally {
        // 无论接口调用成功与否，都清除本地存储
        if (process.client) {
          localStorage.removeItem('token')
          localStorage.removeItem('userInfo')
        }
        this.userInfo = {}
        this.token = ''
        this.hasShop = false // 清除 hasShop 状态

        // 重置标志位
        setTimeout(() => {
          this.isLoggingOut = false;
        }, 1000);
      }
    },
    async userInfoAction() {
      try {
        const token = this.getToken;
        console.log('userInfoAction - token:', token);
        if (!token) {
          console.log('userInfoAction - no token, returning');
          return
        }
        const data = await userProfile({})
        console.log('userInfoAction - data:', data);
        if (data.code === 200 && data.data) {
          const userInfo = data.data;

          // 处理头像：如果是 ossId，转换为 URL
          if (userInfo.avatar && !userInfo.avatar.includes('http')) {
            try {
              const ossRes = await listByIds(userInfo.avatar);
              if (ossRes.data && ossRes.data.length > 0) {
                userInfo.avatar = ossRes.data[0].url;
              }
            } catch (err) {
              console.error('获取头像URL失败:', err);
            }
          }

          this.userInfo = userInfo
          if (process.client) {
            localStorage.setItem('userInfo', JSON.stringify(userInfo))
          }
        }
        return Promise.resolve(data.data)
      } catch (e) {
        console.error('userInfoAction error:', e);
        // 即使获取用户信息失败，也不要清除本地存储的用户信息
        return Promise.reject(e.message)
      }
    },
    async getShopInfo() {
      try {
        const data = await getShopUserInfo()
        console.log('getShopInfo - data:', data);
        if (data.code === 200 && data.data) {
          this.hasShop = data.data.hasShop || false
          this.hasCompany = data.data.hasCompany || false
          console.log('hasShop status:', this.hasShop);
        }
        return Promise.resolve(data.data)
      } catch (e) {
        console.error('getShopInfo error:', e);
        return Promise.reject(e.message)
      }
    }
  },
})